package com.vma.offer.service;

import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.vma.shoes.bizModel.model.Market;
import com.vma.shoes.bizModel.model.Offer2Market;

import java.lang.reflect.Array;
import java.util.*;

/**
 * Created by chenzui on 2017/4/18.
 */
public class MarketService {
    public static Page<Market> qryMarketList(Integer cPage, Integer pSize, String theme, String status, String marketName, String start, String end){
        String condition = "";
        List<String> param = new ArrayList<String>();
        if(status != null && !"".equals(status)){
            condition += "and v_status = ? ";
            param.add(status);
        }
        if(theme != null && !"".equals(theme)){
            condition += "and theme = ? ";
            param.add(theme);
        }
        if(start != null && !"".equals(start)){
            condition += "and create_date > ? ";
            param.add(start);
        }
        if(end != null && !"".equals(end)){
            condition += "and create_date < ? ";
            param.add(end);
        }
        if(marketName != null && !"".equals(marketName)){
            condition += "and market_name like ? ";
            param.add("%"+marketName+"%");
        }

        Page<Market> marketPage = Market.dao.paginate(cPage,pSize,"SELECT id,market_name,market_desc,img_url,theme ",
                "FROM market where 1=1 "+condition+" order by id desc"
                ,param.toArray());
        return marketPage;
    }

    public static List<Record> qryOfferListByMarketId(String marketId){
        List<Record> offers = Db.find("SELECT " +
                "  o.id," +
                "  o.offer_name," +
                "  (select o2m.market_id FROM offer_2_market o2m WHERE o2m.offer_id = o.id AND o2m.status = 1 AND o2m.market_id = ?) market_id " +
                "FROM offer o ",marketId);
        return offers;
    }

    public static void addOfferRela(String offerIds, String marketId) {
        List<Offer2Market> o2m = Offer2Market.dao.find("select * from offer_2_market where market_id =?",marketId);
        if (o2m != null && o2m.size() > 0){
            for (Offer2Market tmp:o2m) {
                tmp.setStatus("0").setUpdateTime(new Date()).update();
            }
        }
        String[] ids = offerIds.split(",");
        for (String id: Arrays.asList(ids)) {
            new Offer2Market().setStatus("1").setMarketId(Integer.valueOf(marketId)).setOfferId(Integer.valueOf(id)).setCreateTime(new Date())
                    .setUpdateTime(new Date()).save();
        }
    }
}
